package com.spcloud.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * https://sentinelguard.io/zh-cn/
 */
public class SentinelDemo {

    public static void main(String[] args)throws Exception {
        // 配置规则.
        initFlowRules();

        for (int i = 1; i <= 15; i++) {

            // 1.5.0 版本开始可以直接利用 try-with-resources 特性
            try (Entry entry = SphU.entry("HelloWorld")) {
                // 被保护的逻辑
                System.out.println("success!" + i);
            } catch (BlockException ex) {
                // 处理被流控的逻辑
                System.out.println("blocked!" + i);
            }
            if (i == 10) {
                System.out.println("begin sleep------");
                TimeUnit.SECONDS.sleep(5);
            }

        }

        for (int i = 1; i <= 10; i++) {

            // 1.5.0 版本开始可以直接利用 try-with-resources 特性
            try (Entry entry = SphU.entry("HelloWorld")) {
                // 被保护的逻辑
                System.out.println("success!" + i);
            } catch (BlockException ex) {
                // 处理被流控的逻辑
                System.out.println("blocked!" + i);
            }
        }


    }


    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(10);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

}
